//index.js
const app = getApp()

const dtFmt = require('../../lib/utils.js')

Page({
  data: {
    bill: {},
  },

  onLoad: function (options) {
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }
    console.log("billPreview options => ", options)
    this.queryData(options)
  },

  queryData: function (options) {
    var _pageOption = this
        wx.getStorage({
          key: 'bill',
          success: function(res) {
            var bill = res.data
            bill.status = 0
            bill.createDate = Date.now()
            _pageOption.setData({
              bill: bill
            })
          },
          complete: function(res) {
            console.log("get storage => ", res)
          }
        })
  },
  billSubmit: function (e) {
    wx.showLoading({
      title: '提交中',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 2000)

    this.data.bill.fee = -1
    this.data.bill.createDate = Date.now()
    this.data.bill.status = 0

    console.log("invoiceBilling submit => ", this.data.bill)

    wx.cloud.callFunction({
      name: 'bill_add',
      data: {
        bill: this.data.bill
      },
      success: res => {
        console.log("invoiceBilling bill_add => ", res)
        if (res.result.code == 1) {
          wx.navigateBack({
            success: function () {
              wx.showToast({
                title: '发票申请已提交',
              })
            }
          })
        }
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '提交失败请重试',
        })
        console.error('[云函数] [bill_add] 调用失败：', err)
      }
    })
  },
})
